package com.streamkar.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.streamkar.entity.base.ResponseData;
import com.streamkar.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName AccountServiceImpl
 * @Description
 * @Author tyfrost
 * @Date 2018/11/14 上午12:12
 * @Version 1.0
 */
@Service
public class AccountServiceImpl implements AccountService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

    private final RestTemplate restTemplate;

    public AccountServiceImpl(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @Override
    public Integer login(String account, String passwd, String loginUrl) {
        ResponseData<String> response = new ResponseData<>();

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("username", account);
        jsonObj.put("password", passwd);
        HttpEntity<String> formEntity = new HttpEntity<>(jsonObj.toString(), headers);
        try {
            ResponseEntity<JSONObject> responseEntity = this.restTemplate.postForEntity(loginUrl, formEntity, JSONObject.class);
            if (null != responseEntity && null != responseEntity.getBody()) {
                LOGGER.info("username:{} login success..", account);
                return responseEntity.getBody().getInteger("userId");
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("username:{},loginurl:{} login catch an exception..", account, loginUrl, e);
            return null;
        }
    }
}
